package com.zhou.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhou.common.constant.ProductConstant;
import com.zhou.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.zhou.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.zhou.gulimall.product.service.AttrAttrgroupRelationService;
import com.zhou.gulimall.product.service.AttrGroupService;
import com.zhou.gulimall.product.service.CategoryService;
import com.zhou.gulimall.product.vo.AttrRespVo;
import com.zhou.gulimall.product.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhou.common.utils.PageUtils;
import com.zhou.common.utils.Query;

import com.zhou.gulimall.product.dao.AttrDao;
import com.zhou.gulimall.product.entity.AttrEntity;
import com.zhou.gulimall.product.service.AttrService;
import org.springframework.util.StringUtils;

@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAll(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            relation.setAttrId(attrEntity.getAttrId());
            relation.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(relation);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type","base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0){
            wrapper.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((wrapper1)->{
                wrapper1.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
               wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = page.getRecords();
        List<AttrRespVo> respVos = list.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity,attrRespVo);
            //根据attrEntity实体类对象的AttrGroupId()查找到对应的attrGroupEntity对象获取AttrGroupName
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("attr_id",attrEntity.getAttrId());
            if ("base".equalsIgnoreCase(type)){
                AttrAttrgroupRelationEntity relation = attrAttrgroupRelationService.getOne(queryWrapper);
                if (relation != null){


                if (relation.getAttrGroupId() != null){
                    attrRespVo.setGroupName( attrGroupService.getById(relation.getAttrGroupId()).getAttrGroupName());
                }
                }
            }
           if (!StringUtils.isEmpty(categoryService.getById(attrEntity.getCatelogId()))){
               attrRespVo.setCatelogName( categoryService.getById(attrEntity.getCatelogId()).getName());
           }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo getdetailById(Long attrId) {
        AttrEntity attrEntity =this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        List<Long> catelogPaths = new ArrayList<>();

        Long  p2 = categoryService.getById(attrEntity.getCatelogId()).getParentCid();

        catelogPaths.add(categoryService.getById(p2).getParentCid());
        catelogPaths.add(p2);
        catelogPaths.add(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(catelogPaths.toArray(new Long[0]));
        /**
         * attrGroupId
         */
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            Long groupId = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id",attrEntity.getAttrId())).getAttrGroupId();
            if (groupId != null){
                attrRespVo.setAttrGroupId(groupId);
                attrRespVo.setGroupName(attrGroupService.getById(groupId).getAttrGroupName());
            }

        }

        return attrRespVo;
    }

    @Override
    public PageUtils querySalePage(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (catelogId != 0){
            wrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((wrapper1)->{
                wrapper1.eq("attr_id",key).or().like("attr_name",key);
            });
        }


        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = page.getRecords();
        return new PageUtils(page);
    }

    /**
     * 根据分组id查找关联的所有基本属性
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> collect = entities.stream().map((attr) -> {
            return attr.getAttrId();

        }).collect(Collectors.toList());
        Collection<AttrEntity> attrEntities = this.listByIds(collect);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void getdetailRelation(AttrAttrgroupRelationEntity[] vos) {
        //attrAttrgroupRelationService.remove(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,))
        relationDao.deleteBatchRelation(Arrays.asList(vos));
    }

    /**
     * 获取当前分组没有关联到的属性
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
        //当前分组只能关联自己所属分类的所有属性
        //只能关联么有被应用的属性t
        Long cateid = attrGroupService.getById(attrGroupId).getCatelogId();
        //找到当前商品下的其他分组
        //这些分组关联的属性= 自己思路方法：先获取groupid=null的所有属性，在取出当前商品id下的属性
        List<AttrAttrgroupRelationEntity> list1 = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().isNull("attr_group_id"));
        List<AttrEntity> list2 = new ArrayList<>();
        AttrEntity attrEntity2 = new AttrEntity();
        for (int i = 0; i < list1.size(); i++) {
            attrEntity2 = this.getById(list1.get(i).getAttrId());
            if (attrEntity2.getCatelogId().equals(cateid)){
                list2.add(attrEntity2);
            }
        }
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("catelog_id",cateid);
        int totalCount = list2.size();
        int pageSize = 10;
        int currPage =Integer.parseInt(params.get("page").toString());
        PageUtils pageUtils = new PageUtils(list2,totalCount,pageSize,currPage);


        return pageUtils;

    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {

        //SELECT * FROM`pms_attr`WHERE attr_id IN (?) AND search_type=1;
        return baseMapper.selectSearchAttrs(attrIds);

    }


}